<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="query.query.orderNo" clearable placeholder="请输入订单编号" />
      <el-input v-model="query.query.outStoreNo" clearable placeholder="请输入出库单号" />
      <el-input v-model="query.query.customerName" clearable placeholder="请输入供应商名称" />
      <el-select v-model="query.query.outStoreState" clearable style="margin-right:10px;" placeholder="请选择出库状态"
        filterable @change="getdata">
        <el-option v-for="item in warehousing" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-date-picker v-model="q_p_formDate1" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange"
        range-separator="-" start-placeholder="申请开始日期" end-placeholder="申请结束日期" @change="q_p_selectTimecreate" />
      <el-button type="primary" icon="el-icon-search" @click="search">
        {{ $t("table.search") }}
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true">
        新增
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleSendOrder">
        生成送货单
      </el-button>
      <el-button @click="handleExport" type="primary" icon="el-icon-download">
        {{ $t("table.export") }}
      </el-button>
      <!-- <el-button type="primary" icon="el-icon-check" @click="dialogVisible = true">
        确认入库
      </el-button> -->
    </div>
    <el-table :data="tableData" row-key="id" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column prop="inoutStoreNo" label="申请单号" /> -->
      <el-table-column label="订单编号" prop="businessNo" />
      <el-table-column label="出库单号" prop="inoutStoreNo" />
      <el-table-column label="物料名称" prop="materialName" />
      <el-table-column label="物料编码" prop="materialNo" />
      <el-table-column prop="applyType" label="出库类型" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ getRkApplyType(row.applyType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="inoutStoreNum" label="出库数量" align="center" width="80" />
      <el-table-column prop="tuihuoNum" label="退货数量" align="center" width="80">
        <template slot-scope="{ row }">
          <span style="color: red;">{{ row.tuihuoNum }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tuihuoState" label="退货状态" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.applyType == 9 ? row.tuihuoState == 1 ? '已退货' : '未退货' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" prop="fromWarehouseName" />
      <el-table-column label="客户名称" prop="partnerName" />
      <el-table-column prop="inoutStoreState" label="出库状态" align="center" width="80">
        <template slot-scope="{ row: { inoutStoreState } }">
          {{ inoutStoreState == 0 ? "待出库" : "已出库" }}
        </template>
      </el-table-column>
      <el-table-column label="订单日期" prop="orderDate">
        <template slot-scope="{ row }">
          <span>{{
        row.orderDate | parseTime("{y}-{m}-{d}")
      }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出库申请时间" prop="applyTime">
        <template slot-scope="{ row }">
          <span>{{
          row.applyTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
        }}</span>
        </template>
      </el-table-column>
      <el-table-column label="确认出库时间" prop="replyTime">
        <template slot-scope="{ row }">
          <span>{{
          row.replyTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
        }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="180">
        <template slot-scope="{ row, $index }">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row, $index)">
            {{ $t('table.edit') }}
          </el-button> -->
          <el-button type="primary"  size="mini" :disabled="row.inoutStoreState != 0"
            @click="handleOutStoreConfirm(row)">
            {{row.applyType == 9 ? '退货确认' : '出库确认'}}
          </el-button>
          <el-button type="danger" :disabled="row.inoutStoreState != '0'" size="mini" @click="handleDel(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
    <el-dialog width="80%" :close-on-click-modal="false" :visible.sync="dialogVisible" @closed="handleCloseRk"
      title="出库">
      <el-form ref="ruleForm" :rules="rules" :model="project" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库类型" prop="applyType">
              <el-select style="width: 100%;" v-model="project.applyType" filterable placeholder="请选择入库类型" clearable>
                <el-option v-for="item in applyTypeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库商品" prop="materialId">
              <el-select style="width: 100%;" v-model="project.materialId" filterable placeholder="请选择出库商品" clearable
                @change="getWmsStockChangeInStoreList">
                <el-option v-for="item in materialList" :key="item.id" :label="item.materialName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!project.applyType || project.applyType === '5'">
          <el-col :span="12">
            <el-form-item label="源头仓库" prop="fromWarehouseId">
              <el-select style="width: 100%;" v-model="project.fromWarehouseId" filterable placeholder="请选择源头仓库"
                clearable @change="getWmsStockChangeInStoreList">
                <el-option v-show="item.id !== project.toWarehouseId && item.state == '1'
        " v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标仓库" prop="toWarehouseId">
              <el-select style="width: 100%;" v-model="project.toWarehouseId" filterable placeholder="请选择目标仓库"
                clearable>
                <el-option v-show="project.fromWarehouseId !== item.id && item.state == '1'
        " v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col :span="12">
            <el-form-item label="源头仓库" prop="fromWarehouseId">
              <el-select style="width: 100%;" v-model="project.fromWarehouseId" filterable placeholder="请选择源头仓库"
                clearable @change="getWmsStockChangeInStoreList">
                <el-option v-show="item.id !== project.toWarehouseId && item.state == '1'
        " v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="rkTableData" row-key="id" highlight-current-row border
        @selection-change="rkHandleSelectionChange" :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }" ref="multipleTable">
        <el-table-column type="selection" width="55" :selectable="selectableStatus" />
        <el-table-column prop="warehouseName" label="仓库" width="220" />
        <el-table-column prop="inoutStoreNo" label="入库单号" width="160" />
        <el-table-column prop="materialNo" label="商品编码" />
        <el-table-column prop="materialName" label="商品名称" />
        <el-table-column prop="batchNumber" label="批次号" />
        <el-table-column prop="changeType" label="入库类型">
          <template slot-scope="{ row }">
            <span>{{ getRkApplyType(row.changeType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="changeNum" label="入库数量" />
        <el-table-column prop="leftNum" label="剩余数量" />
        <el-table-column prop="inoutStoreNum" label="出库数量" width="150">
          <template slot-scope="{row}">
            <el-input clearable v-model.trim="row.inoutStoreNum" size="small"
              @input="row.inoutStoreNum = row.inoutStoreNum.replace(/[^\d|\.]/g, '')" placeholder="请输入出库数量" />
          </template>
        </el-table-column>
        <el-table-column prop="changeTime" label="入库日期" width="160">
          <template slot-scope="{row}">
            <span>{{ row.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="rkTotal" :total="rkTotal" :page.sync="rkQuery.pageIndex" :limit.sync="rkQuery.pageSize"
        @pagination="getWmsStockChangeInStoreList" />
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="dialogVisible = false">
          {{ $t("permission.cancel") }}
        </el-button>
        <el-button type="primary" @click="submit">
          {{ $t("permission.save") }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog width="80%" @closed="handleClose" :close-on-click-modal="false" :visible.sync="rkDialogVisible"
      :title="rkForm.applyType == 9 ? '退货确认' : '出库确认'">
      <el-form ref="rkRuleForm" :rules="rkRules" :model="rkForm" label-width="80px">
      <el-form-item v-if="rkForm.applyType != 9" label="仓库" prop="warehouseId">
        <el-select style="width: 100%;" v-model="rkForm.warehouseId" @change="changeWarehouse" filterable
          placeholder="请选择仓库" clearable>
          <el-option v-for="item in rkTableFormData" :key="item.warehouseId" :label="item.warehouseName"
            :value="item.warehouseId" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="rkForm.applyType != 9" label="出库单号" prop="outStoreNo">
       <el-input v-model="rkForm.outStoreNo" size="small" placeholder="请输入出库单号" />
      </el-form-item>
      <el-form-item v-if="rkForm.applyType == 9" label="退货单号" prop="huiHuoBillNo">
       <el-input v-model="rkForm.huiHuoBillNo" size="small" placeholder="请输入退货单号" />
      </el-form-item>
      </el-form>
      <el-table v-if="rkForm.applyType != 9" :data="rkTableData" row-key="id" highlight-current-row border
        @selection-change="rkHandleSelectionChange" :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }" ref="multipleTable">
        <el-table-column type="selection" width="55" :selectable="selectableStatus" />
        <el-table-column prop="warehouseName" label="仓库" width="220" />
        <el-table-column prop="inoutStoreNo" label="入库单号" width="160" />
        <el-table-column prop="materialNo" label="商品编码" />
        <el-table-column prop="materialName" label="商品名称" />
        <el-table-column prop="batchNumber" label="批次号" />
        <el-table-column prop="changeType" label="入库类型">
          <template slot-scope="{ row }">
            <span>{{ getRkApplyType(row.changeType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="changeNum" label="入库数量" />
        <el-table-column prop="leftNum" label="剩余数量" />
        <el-table-column prop="outStoreNum" label="出库数量" width="150">
          <template slot-scope="{row}">
            <el-input clearable v-model.trim="row.outStoreNum" size="small"
              @input="row.outStoreNum = row.outStoreNum.replace(/[^\d|\.]/g, '')" placeholder="请输入出库数量" />
          </template>
        </el-table-column>
        <el-table-column prop="changeTime" label="入库日期" width="160">
          <template slot-scope="{row}">
            <span>{{ row.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="rkTotal && rkForm.applyType != 9" :total="rkTotal" :page.sync="rkQuery.pageIndex" :limit.sync="rkQuery.pageSize"
        @pagination="getWmsStockChangeInStoreList" />
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="rkDialogVisible = false">
          {{ $t("permission.cancel") }}
        </el-button>
        <el-button type="primary" @click="rkSubmit">
          {{ $t("permission.save") }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog width="80%" :close-on-click-modal="false" :visible.sync="thDialogVisible" title="退货">
      <el-table :data="thTableData" row-key="id" highlight-current-row border
        @selection-change="thHandleSelectionChange" :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }" ref="multipleTable">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouseName" label="仓库" width="220" />
        <el-table-column prop="inoutStoreNo" label="出库单号" width="160" />
        <el-table-column prop="materialNo" label="商品编码" />
        <el-table-column prop="materialName" label="商品名称" />
        <el-table-column prop="changeType" label="出库类型">
          <template slot-scope="{ row }">
            <span>{{ getRkApplyType(row.changeType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="changeNum" label="出库数量" />
        <el-table-column prop="leftNum" label="剩余数量" />
        <el-table-column prop="inoutStoreNum" label="退货数量" width="150">
          <template slot-scope="{row}">
            <el-input clearable v-model.trim="row.inoutStoreNum" size="small"
              @input="row.inoutStoreNum = row.inoutStoreNum.replace(/[^\d|\.]/g, '')" placeholder="请输入退货数量" />
          </template>
        </el-table-column>
        <el-table-column prop="changeTime" label="出库日期" width="160">
          <template slot-scope="{row}">
            <span>{{ row.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="thDialogVisible = false">
          {{ $t("permission.cancel") }}
        </el-button>
        <el-button type="primary" @click="thSubmit">
          {{ $t("permission.save") }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="送货单格式" :visible.sync="orderVisible" @closed="orderHandleClose" width="500px" :close-on-click-modal="false">
      <el-form ref="orderRuleForm" :model="orderForm" :rules="orderRules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="送货单格式" prop="downloadMode">
              <el-radio-group v-model="orderForm.downloadMode">
                <el-radio label="EXCEL">excel</el-radio>
                <el-radio label="PDF">pdf</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderVisible = false">取 消</el-button>
        <el-button type="primary" @click="orderSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  tuiHuoConfirm,
  pageOutstoreList,
  generalSendGoodsBill,
  outStoreConfirm,
  codeWarehousePageList,
  codeMaterialListAll,
  wmsStoreApplyAdd,
  wmsStockWareHouseList,
  wmsStockChangeInStoreList,
  wmsStockApplyChangeList,
  wmsStockApplyExportInStoreExcel,
  wmsStoreApplyDel
} from "@/api/qmsQualityManagement";
import { downfile } from "@/utils";

const project = {
  id: 0,
  close: "",
  referCost: "",
  acceptAppeal: 0,
  appeal: 0
};

export default {
  name: "Project",
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      orderVisible: false,
      orderForm: {
        downloadMode: 'EXCEL'
      },
      applyTypeList: [{
        label: '调拨出库',
        value: '5'
      }, {
        label: '其他出库',
        value: '7'
      }],
      q_p_formDate1: [],
      rules: {
        applyType: [
          { required: true, message: "请选择入库类型", trigger: "change" }
        ],
        materialId: [
          { required: true, message: "请选择出库商品", trigger: "change" }
        ],
        inoutStoreNum: [
          { required: true, message: "请输入出库数量", trigger: "blur" }
        ],
        fromWarehouseId: [
          { required: true, message: "请选择源头仓库", trigger: "blur" }
        ],
        toWarehouseId: [
          { required: true, message: "请选择目标仓库", trigger: "blur" }
        ]
      },
      warehousing: [
        {
          label: "待出库",
          value: "0"
        },
        {
          label: "已出库",
          value: "1"
        }
      ],
      solutionList: [
        {
          value: "索赔"
        },
        {
          value: "补货"
        },
        {
          value: "补货并索赔"
        },
        {
          value: "返工返修"
        }
      ],
      list: [],
      query: {
        pageIndex: 1,
        pageSize: 20,
        query: {
          inOut: 2,
          startDate: null,
          endDate: null
        }
      },
      total: 0,
      dialogVisible: false,
      project: {},
      tableData: [],
      selectedList: [],
      warehouseList: [],
      warehousequery: {
        pageIndex: 1,
        pageSize: 1000000,
        query: {}
      },
      materialList: [],
      rkDialogVisible: false,
      rkTableData: [],
      rkTableFormData: [],
      rkForm: {},
      rkRules: {
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" }
        ],
        outStoreNo:[
          { required: true, message: "请输入出库单号", trigger: "blur" }
        ],
        huiHuoBillNo:[
          { required: true, message: "请输入退货单号", trigger: "blur" }
        ]
      },
      rkQuery: {
        pageIndex: 1,
        pageSize: 10,
        query: {}
      },
      rkSelectedListData: [],
      outStoreApplyId: null,
      ckTableData: [],
      thTableData: [],
      thDialogVisible: false,
      thSelectedListData: [],
      thId: null,
      thWarehouseId: null,
      materialId: null
    };
  },
  computed: {},
  mounted() {
    this.getday()
    this.getInfo();
    this.getUserPage();
    this.getCodeMaterialListAll();
  },
  methods: {
    async handleExport() {
      try {
        const {query} = this.query
        await wmsStockApplyExportInStoreExcel(
          query
        )
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile('出库.xlsx', err);
          }
        }
      }
    },
    orderSure() {
      this.$refs["orderRuleForm"].validate(async valid => {
        if (valid) {
          try {
            await generalSendGoodsBill(this.selectedList.join(','),this.orderForm.downloadMode);
          } catch (err) {
            const reader = new FileReader();
            reader.readAsText(err);
            reader.onload = (event) => {
              const resultString = reader.result; // 这里就是转换后的字符串
              if (resultString.includes('code') && resultString.includes('isSuccess')) {
                this.$message.error(JSON.parse(resultString).message)
              } else {
                const n = this.orderForm.downloadMode == 'EXCEL' ? '送货单.xlsx' : '送货单.pdf'
                downfile(n, err);
                this.orderVisible = false
              }
            }
          }
        }
      })
    },
    orderHandleClose() {
      this.orderForm = {
        downloadMode: 'EXCEL'
      };
      this.$refs["orderRuleForm"].resetFields();
    },
    thHandleSelectionChange(e) {
      this.thSelectedListData = [];
      e.forEach(item => {
        this.thSelectedListData.push(item);
      });
    },
    async thSubmit() {
      if (!this.thSelectedListData.length) {
        this.$message.warning("请至少选择一条出库记录！");
        return;
      }
      try {
        let batchVoList = []
        this.thSelectedListData.forEach(item => {
          if (!item.inoutStoreNum) {
            this.$message.error('请输入退货数量！')
            throw new Error()
          }
          batchVoList.push({
            changeId: item.id,
            batchNumber: item.batchNumber,
            inoutStoreNum: item.inoutStoreNum
          })
        })
        await wmsStoreApplyAdd({
          applyType: '8',
          materialId: this.materialId,
          fromWarehouseId: this.thWarehouseId,
          batchVoList
        })
        this.$message.success('操作成功！')
        this.thDialogVisible = false
        this.getInfo()
      } catch (err) {

      }
    },
    async getWmsStockApplyChangeList() {
      this.thTableData = await wmsStockApplyChangeList(this.thId, '2')
      if (this.thTableData.length) {
        this.thTableData.forEach(item => {
          this.$set(item, 'inoutStoreNum', item.changeNum)
        })
      }
    },
    handleCloseRk() {
      this.rkQuery = {
        pageIndex: 1,
        pageSize: 10,
        query: {}
      }
      this.project = {}
      this.generateTableData = [{
        inoutStoreNum: '',
        batchNumber: ''
      }]
      this.rkTableData = []
      this.$refs['ruleForm'] && this.$refs['ruleForm'].resetFields();
    },
    handleCancelOrder(row) {
      this.thId = row.idStr
      this.materialId = row.materialId
      this.thWarehouseId = row.warehouseId
      this.getWmsStockApplyChangeList()
      this.thDialogVisible = true
    },
    handleClose() {
      this.rkQuery = {
        pageIndex: 1,
        pageSize: 10,
        query: {}
      }
      this.outStoreApplyId = null
      this.rkTableData = []
      this.$refs['rkRuleForm'].resetFields();
    },
    changeWarehouse(e) {
      this.rkQuery.query.warehouseId = e
      this.rkQuery.pageIndex = 1
      this.getWmsStockChangeInStoreList()
    },
    getRkApplyType(val) {
      if (val == 1) {
        return "销售出库";
      } else if (val == 2) {
        return "采购入库";
      } else if (val == 4) {
        return "调拨入库";
      } else if (val == 5) {
        return "调拨出库";
      } else if (val == 6) {
        return "其他入库";
      } else if (val == 7) {
        return "其他出库"
      } else if (val == 8) {
        return "销售退货入库";
      } else if (val == 9) {
        return "采购退货出库";
      }
    },
    getday() {
      // const currDate = new Date().toLocaleDateString()// 2020/11/6
      // const arrs = currDate.split('/')
      // const arrs1 = arrs.join('-')
      // this.query.query.beginDate = this.query.query.endDate = arrs1
      // this.q_p_formDate1 = [arrs1, arrs1]
      const currDate = new Date().toLocaleDateString()// 2020/11/6
      const arrs = currDate.split('/')
      const arrs1 = arrs.join('-')
      const yy = parseInt(arrs[0]);
      const mm = parseInt(arrs[1]);
      const dd = parseInt(arrs[2]);
      const pdStr = new Date(yy, mm - 1, 1).toLocaleDateString().split('/').join('-');
      this.query.query.startDate = pdStr
      this.query.query.endDate = arrs1
      this.q_p_formDate1 = [pdStr, arrs1]
    },
    q_p_selectTimecreate(val) {
      const { query } = this.query
      if (val) {
        query.startDate = val[0]
        query.endDate = val[1]
      } else {
        query.startDate = query.endDate = ''
      }
    },
    async rkSubmit() {
      if(this.rkForm.applyType == 9){
        await tuiHuoConfirm({
          id:this.outStoreApplyId,
          huiHuoBillNo:this.rkForm.huiHuoBillNo
        })
        this.getInfo();
        this.$message.success("操作成功！");
        this.rkDialogVisible = false
      }else{
        if (!this.rkSelectedListData.length) {
        this.$message.warning("请至少选择一条入库记录！");
        return;
      }
      let outStoreVoList = []
      try {
        this.rkSelectedListData.forEach(item => {
          if (!item.outStoreNum) {
            this.$message.warning("出库数量不能为空！");
            throw new Error()
          }
          outStoreVoList.push({
            inStoreId: item.id,
            outStoreNum: item.outStoreNum
          })
        })
      } catch (err) {
        outStoreVoList = []
      }

      this.$confirm("确认出库, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await outStoreConfirm({
          outStoreApplyId: this.outStoreApplyId,
          outStoreVoList
        });
        this.getInfo();
        this.$message.success("操作成功！");
        this.rkDialogVisible = false
      });
      }
    },
    validateInteger(value) {
      if (value < 1) {
        this.project.inoutStoreNum = 1;
      } else {
        const numValue = parseInt(value, 10);
        if (!Number.isNaN(numValue)) {
          this.project.inoutStoreNum = numValue;
        } else {
          this.project.inoutStoreNum = 1;
        }
      }
    },
    async getCodeMaterialListAll() {
      this.materialList = await codeMaterialListAll();
    },
    async getUserPage() {
      const { records } = await codeWarehousePageList(this.warehousequery);
      this.warehouseList = records;
    },
    async handleSendOrder() {
      if (!this.selectedList.length) {
        this.$message.warning("请至少选择一条订单");
        return;
      }
      this.orderVisible = true
    },
    handleSelectionChange(e) {
      this.selectedList = [];
      e.forEach(item => {
        this.selectedList.push(item.idStr);
      });
    },
    rkHandleSelectionChange(e) {
      this.rkSelectedListData = [];
      e.forEach(item => {
        this.rkSelectedListData.push(item);
      });
    },
    handleDel({id}){
      this.$confirm("确认删除出库明细?", "警告", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          }).then(async () => {
            wmsStoreApplyDel(id).then(res => {
              this.getInfo();
              this.$message.success("删除成功");
            });
          });
    },
    async handleOutStoreConfirm({ idStr, materialId, applyType }) {
      this.rkTableFormData = await wmsStockWareHouseList(materialId, '2')
      this.outStoreApplyId = idStr
      this.rkQuery.pageIndex = 1
      this.rkQuery.query.materialId = materialId
      this.rkForm.applyType = applyType
      await this.getWmsStockChangeInStoreList()
      this.rkDialogVisible = true
    },
    async getWmsStockChangeInStoreList() {
      const { materialId, fromWarehouseId } = this.project
      if (this.outStoreApplyId) {
        const { records, total } = await wmsStockChangeInStoreList(this.rkQuery)
        records.forEach(item => {
          this.$set(item, 'outStoreNum', item.leftNum)
        })
        this.rkTotal = total
        this.rkTableData = records
      } else if (materialId && fromWarehouseId) {
        const { records, total } = await wmsStockChangeInStoreList({
          ...this.rkQuery,
          query: {
            materialId: this.project.materialId,
            warehouseId: this.project.fromWarehouseId
          }
        })
        records.forEach(item => {
          this.$set(item, 'inoutStoreNum', item.leftNum)
        })
        this.rkTotal = total
        this.rkTableData = records
      }
    },
    handleSizeChange(siez) {
      this.query.pageSize = size;
      this.getInfo();
    },
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage;
      this.getInfo();
    },
    submit() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          try {
            const {
              applyType,
              materialId,
              fromWarehouseId,
              toWarehouseId
            } = this.project;
            let params = {
              applyType,
              materialId,
              fromWarehouseId,
              batchVoList: []
            }
            if (applyType == '5') params.toWarehouseId = toWarehouseId
            this.rkSelectedListData.forEach(item => {
              if (!item.inoutStoreNum) {
                this.$message.warning("出库数量不能为空！");
                throw new Error()
              }
              params.batchVoList.push({
                changeId: item.id,
                batchNumber: item.batchNumber,
                inoutStoreNum: item.inoutStoreNum
              })
            })
            await wmsStoreApplyAdd(params);
            this.dialogVisible = false;
            this.getInfo();
            this.$message.success("操作成功！");
          } catch (err) {

          }
        }
      });
    },
    handleUpdate(row, $index) {
      this.dialogVisible = true;
    },
    search() {
      this.query.pageIndex = 1;
      this.getInfo();
    },
    getInfo() {
      pageOutstoreList(this.query).then(res => {
        const { records, total } = res;
        this.tableData = records;
        this.total = total;
      });
    }
  }
};
</script>

<style scoped>
.addinput /deep/ .el-input__inner {
  border: none;
  background: #f5f7fa;
}

.addinput /deep/ .el-textarea__inner {
  border: none;
  background: #f5f7fa;
}

.downfile {
  text-decoration: underline;
  color: blue;
}
</style>
